package io.e2x.testground.fruitstore.service.impl;


import io.e2x.testground.fruitstore.dal.entities.Sku;
import io.e2x.testground.fruitstore.dal.entities.StoreSpu;
import io.e2x.testground.fruitstore.repo.SkuRepo;
import io.e2x.testground.fruitstore.repo.StoreSpuRepo;
import io.e2x.testground.fruitstore.service.ProductService;
import io.e2x.testground.fruitstore.service.StoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

@Component
public class ProductServiceImpl implements ProductService {

    @Autowired
    SkuRepo skuRepo;

    @Autowired
    StoreService storeService;

    @Override
    public Mono<Void> addSpu(StoreSpu storeSpu, Sku sku) {
        return skuRepo.save(sku)
                .flatMap(sku1 -> storeService.addStoreSpus(storeSpu.setSkuId(sku1.getId())))
                .doOnSuccess(v -> System.out.printf("添加成功  %s%n", sku));
    }

    @Override
    public Mono<Void> updateSpu(StoreSpu storeSpu, Sku sku) {
        return skuRepo.findByNameAndStoreId(sku.getName(), storeSpu.getStoreId()).flatMap(sku1 -> {
            sku1.setName(sku.getName());
            sku1.setPrice(sku.getPrice());
            sku1.setStock(sku.getStock());
            sku1.setCount(sku.getCount());
            return skuRepo.save(sku1);
        }).then(storeService.updateStoreSpus(storeSpu)).then();
    }

    @Override
    public Mono<Void> deleteSpu(StoreSpu storeSpu) {
        return storeService.deleteStoreSpus(storeSpu).then(skuRepo.deleteById(storeSpu.getSkuId())).then();
    }

    @Override
    public Mono<StoreSpu> findBySpuNo(String spuNo) {
        return storeService.findStoreSpuBySpuNo(spuNo);
    }

    @Override
    public Mono<StoreSpu> findBySpuName(String name) {
        return skuRepo.findByName(name).flatMap(sku -> storeService.findStoreSpuBySkuId(sku.getId()));
    }
}
